package com.nameli.admin.config.filter;

import com.alibaba.fastjson.JSONObject;
import com.nameli.SIM.util.*;
import com.nameli.admin.config.shiro.auth.AuthToken;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;


import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author NAME-L
 * @Description TODO
 * @className AuthFilter
 * @date 2021-12-31 16:23:19
 */
public class AuthFilter extends BasicHttpAuthenticationFilter {

    private static final Log logger = LogFactory.getLog(AuthFilter.class);


    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        //获取请求token
        String token = TokenUtil.getRequestToken((HttpServletRequest) request);
        return new AuthToken(token);
    }

    /**
     * 步骤1.所有请求全部拒绝访问
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) {
            return true;
        }
        return false;
    }


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //获取请求token，如果token不存在，直接返回
        String token = TokenUtil.getRequestToken((HttpServletRequest) request);
        logger.info("从前端获取的token：" + token);
        if (EmptyUtil.isEmpty(token)) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtil.getOrigin());
            httpResponse.setCharacterEncoding("UTF-8");
            httpResponse.setContentType("application/json");
            JSONObject result = new JSONObject();
            result.put("errorCode",ReturnStatus.NO_LOGIN);
            result.put("errorMsg", "验证失败，token为空，请重新登录");
            httpResponse.getOutputStream().write(result.toString().getBytes());
            httpResponse.getOutputStream().close();
            logger.info("onLoginFailure -------->  验证失败，token为空，请重新登录");
            return false;
        }
        return executeLogin(request, response);
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtil.getOrigin());
        httpResponse.setCharacterEncoding("UTF-8");
        try {
            //处理登录失败的异常
            JSONObject result = new JSONObject();
            result.put("errorCode",ReturnStatus.NO_LOGIN);
            result.put("status",0);
            result.put("errorMsg", "登录失败");
            httpResponse.getOutputStream().write(result.toString().getBytes());
            httpResponse.getOutputStream().close();
            logger.info("onLoginFailure -------->  登录失败");
        } catch (IOException exception) {
            exception.printStackTrace();
            logger.error("e:" + e);
        }
        logger.error("Validate token fail, token:" + token.toString() +'\n'+ "error:" + e.getMessage());
        return false;
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(Integer.parseInt(ReturnStatus.SUCCESS));
            return false;
        }
        return super.preHandle(request, response);
    }

}
